#include "dataconverter.hpp"

DataConverter::DataConverter(const QByteArray &_header, const size_t &_len,
                             const DataConvertType &_type)
    : QObject(), header(_header), len(_len), type(_type) {}

void DataConverter::next() {
  isUpdate = false;
  return;
}

DataConverter &DataConverter::operator<<(const QByteArray &data) {
  buf.append(data);
  return *this;
}

bool DataConverter::has() const {
  if (isUpdate)
    return true;

  int ifind = buf.indexOf(header);
  if (ifind == -1)
    return false;

  if (buf.size() - ifind < len + header.size())
    return false;

  frame_buf = buf.mid(ifind + header.size(), len);
  isUpdate = true;
  buf.remove(0, ifind + header.size() + len);
  return true;
}
void DataConverter::beginPush() {
  isWriting = true;
  frame_buf.clear();
  frame_buf.reserve(len);
  buf.clear();
}
void DataConverter::endPush() {
  isWriting = false;
  buf.append(header);
  buf.append(frame_buf);
}

void DataConverter::clear() { buf.clear(); }
const QByteArray &DataConverter::buffer() const { return buf; }